<?php

ini_set("memory_limit", "100M");
ini_set("max_execution_time", 36000);

require_once('../../config/maptrick.conf.php');
require_once(SITE_ROOT . 'lib/PHT.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');
require_once(SITE_ROOT . 'class/bean/Division.class.php');
require_once(SITE_ROOT . 'class/bean/League.class.php');
require_once(SITE_ROOT . 'class/db/DBCountry.class.php');
require_once(SITE_ROOT . 'class/db/DBDivision.class.php');
require_once(SITE_ROOT . 'class/db/DBLeague.class.php');

try {
	if ($_GET["pass"] != SCRIPT_PWD) die("Incorrect password");
	
	$HT = new CHPPConnection(CONSUMERKEY, CONSUMERSECRET);
	$HT->setOauthToken(USERTOKEN);
	$HT->setOauthTokenSecret(USERTOKENSECRET);
	
	for ($i=1; $i<=254318; $i+=100) {
		try {
			if ($HT instanceof CHPPConnection) {
				storeLeagues($i, $i+100, $HT);
				$HT->clearLeagues();
			}
			else break 1;
		}
		catch (Exception $e) {}
	}
	echo "Leagues scanned<br />";
	calculateDivisionSizes();
}
catch (Exception $e) {
	echo $e->getMessage();
}

function storeLeagues($start, $end, $HT) {
	$leagues = new ArrayObject();
	$divisions = new ArrayObject();
	for ($i=$start; $i<=$end; $i++) {
		try {
			$country = new Country();
			$country->setCountryID($HT->getLeague($i)->getLeagueId());
			$division = new Division();
			$division->setCountry($country);
			$division->setDivisionID($HT->getLeague($i)->getLeagueLevel());
			$division->setClosed($HT->getLeague($i)->getLeagueLevel() > $HT->getLeague($i)->getMaxLevel());
			$divisions->append($division);
			$league = new League();
			$league->setDivision($division);
			$league->setLeagueID($HT->getLeague($i)->getLeagueLevelId());
			$league->setName($HT->getLeague($i)->getLeagueLevelName());
			$leagues->append($league);
		}
		catch (Exception $e) {
			echo $e->getMessage();
		}
	}
	$dbdivision = new DBDivision();
	$dbdivision->saveDivisions($divisions);
	$dbleague = new DBLeague();
	$dbleague->saveLeagues($leagues);
	unset($leagues, $divisions, $dbleague, $dbdivision);
}

function calculateDivisionSizes() {
	try {
		$dbcountry = new DBCountry();
		$dbdivision = new DBDivision();
		$dbleague = new DBLeague();
		
		$countries = $dbcountry->getCountries();
		foreach ($countries as $country) {
			$divisions = $dbdivision->getDivisionsByCountry($country);
			foreach ($divisions as $division) {
				$leagues = $dbleague->getLeaguesByDivision($division);
				$division->setSize(count($leagues));
			}
			$dbdivision->saveDivisions($divisions);
		}
		
		$newmoon = new Country();
		$newmoon->setCountryID(90);
		$dbleague->deleteLeaguesByCountry($newmoon);
		$dbdivision->deleteDivisionsByCountry($newmoon);
		
		echo "Sizes of divisions calculated<br />";
	}
	catch (Exception $e) {
		echo $e->getMessage();
	}
}

?>